package com.ht.managermentserver.config;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 后端转发前端vue的路由
 *
 * <p>除了路由做转发以外,其他均不做转发
 *
 * @author czy
 * @package com.ht.managermentserver.filter
 * @date 2020/6/3 10:22
 */
public class VueRouterRewriteFilterConfig implements Filter {
  /**
   * vue ui 的前缀
   */
  public static final String VUE_PREFIX = "ui";

  private static String vue_prefix = null;

  @Override
  public void init(final FilterConfig cfg) throws ServletException {
    // 初始化拦截配置
    vue_prefix = cfg.getInitParameter(VUE_PREFIX);
    if (vue_prefix == null) {
      vue_prefix = "";
    }
  }

  @Override
  public void doFilter(
      final ServletRequest req, final ServletResponse resp, final FilterChain chain)
      throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) req;
    final String servletPath = request.getServletPath();
    final String context = request.getContextPath();
    // 匹配的路径重写
    if (isMatches(servletPath)) {
      req.getRequestDispatcher(context + "/" + vue_prefix + "/index.html").forward(req, resp);
    } else {
      chain.doFilter(req, resp);
    }
  }

  private boolean isMatches(final String url) {
    if (null == vue_prefix || vue_prefix == "") {
      return false;
    }

    return url.contains(vue_prefix + "/")
      && !url.contains("/" + vue_prefix + "/static/")
      && !url.contains("/" + vue_prefix + "/favicon.ico");
  }

  @Override
  public void destroy() {}
}
